/*
 * Copyright 2011-2012 Redia A/S
 * 
 * This file is part of Redias Library App for Android.
 *
 *  Redia Library App for Android is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Redia Library App for Android is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License
 *  along with Redia Library App for Android.  If not, see <http://www.gnu.org/licenses/>.
 */
package dk.redia.libraryapp;

import java.io.ByteArrayOutputStream;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import dk.redia.lib.utils.AppApplication;
import dk.redia.lib.utils.Base64;
import dk.redia.libraryapp.activityutils.LibraryAppActivity;
import dk.redia.libraryapp.model.Externals;
import dk.redia.libraryapp.model.ExternalsReviewItem;

public class ReviewsActivity extends LibraryAppActivity {

	public static final String EXTRAS_KEY_EXTERNALS = "externals";

	private static final String logTag = "ReviewsActivity";

	private Externals externals;
	
	private LinearLayout mainLinearLayout;
	private LayoutInflater inflater;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);

	    externals = getIntent().getParcelableExtra(EXTRAS_KEY_EXTERNALS);
	    if (externals==null) {
	    	Log.e(logTag, "No externals data provided");
	    	finish();
	    }

	    setContentView(R.layout.reviewsactivity);
	    
	    mainLinearLayout = (LinearLayout)findViewById(R.id.reviewsActivityMainLinearLayout);
	    
	    inflater = (LayoutInflater)getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
	    
	    for (final ExternalsReviewItem reviewItem : externals.getReviewItems()) {
			RelativeLayout itemLayout = (RelativeLayout)inflater.inflate(R.layout.reviewitem, null);
			WebView v = (WebView)itemLayout.findViewById(R.id.reviewItemTextWebView);
			View overlay = itemLayout.findViewById(R.id.reviewItemOverlayRelativeLayout);
								
			int col = getResources().getColor(R.color.customerPrimaryColor);
			int red = (col >> 16) & 0xFF;
			int green = (col >> 8) & 0xFF;
			int blue = col & 0xFF;
			
			int backgroundCol = getResources().getColor(R.color.globalBackgroundColor);
			int backgroundRed = (backgroundCol >> 16) & 0xFF;
			int backgroundGreen = (backgroundCol >> 8) & 0xFF;
			int backgroundBlue = backgroundCol & 0xFF;
			
			
			String html = "";
		   
			//v.setBackgroundResource(R.color.defaultTextColor);
		    v.setBackgroundColor(getResources().getColor(R.color.globalBackgroundColor));
		    
		    itemLayout.setTag(reviewItem);
		    overlay.setTag(reviewItem);
		    v.setTag(reviewItem);
		    
		    overlay.bringToFront();
		    
		    final View.OnClickListener listener;
		    
		    if (reviewItem.getSource().equals(ExternalsReviewItem.SOURCE_INFOMEDIA)) {	

				Drawable d = AppApplication.getAppContext().getResources().getDrawable(R.drawable.infomedia_logo_transp);
			    Bitmap b = ((BitmapDrawable)d).getBitmap();
			    ByteArrayOutputStream stream = new ByteArrayOutputStream();
			    b.compress(CompressFormat.PNG, 100, stream);
			    final byte[] logoImageData = stream.toByteArray();
		    	
		    	html = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" +
						"<html>\n" +
						"<head>\n" +
						"<style type=\"text/css\">\n" +
						".infomedia_HeadLine { visibility: collapse; }\n" +
						".infomedia_subHeadLine { visibility: collapse; }\n" +
						".infomedia_ByLine { visibility: collapse; }\n" +
						".infomedia_DateLine { visibility: collapse; }\n" +
						".infomedia_paper { text-transform:uppercase; color: rgb(" + red + "," + green + "," + blue + "); font-size: 18px; position: fixed; top: 10px; }" +
						".infomedia_hedline {}\n" +
						".providerlogo { position: fixed; top: 35px; }\n" + 
						"#p1 { visibility: visible; }\n" + 
						"p { visibility: collapse; }\n" +
						"body { color: white; background-color: rgb(" + backgroundRed + "," + backgroundGreen + "," + backgroundBlue + "); font-family:helvetica neue,arial,sans-serif;font-size:12px }\n" +
						"</style>\n" +
						"</head>\n" +
						"<body>\n" + 
						"<img class=\"providerlogo\" src=\"data:image/png;base64," + Base64.encodeToString(logoImageData, Base64.DEFAULT) + "\" />\n" + 
						reviewItem.getReview() + 
						"</body></html>";
		    	
		    	listener = new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						ExternalsReviewItem eri = (ExternalsReviewItem)v.getTag();
						Intent i = new Intent(ReviewsActivity.this, InfoMediaReviewActivity.class);
						i.putExtra(InfoMediaReviewActivity.EXTRA_EXTERNALS_REVIEW_ITEM, reviewItem);
						startActivity(i);
					}
				};
				
				// Duplicated below, because listener must be final (and sure to be defined)
				v.setOnTouchListener(new View.OnTouchListener() {
					
					@Override
					public boolean onTouch(View v, MotionEvent event) {
						if (event.getAction()==MotionEvent.ACTION_DOWN) {
							listener.onClick(v);
							return true;
						} else {
							return false;
						}
					}
				});
			    v.setOnClickListener(listener);
			    itemLayout.setOnClickListener(listener);
			    overlay.setOnClickListener(listener);
			    // End of duplicated code
		    } else if (reviewItem.getSource().equals(ExternalsReviewItem.SOURCE_LITTERATURSIDEN)) {
		    	
				Drawable d = AppApplication.getAppContext().getResources().getDrawable(R.drawable.litteratursiden_logo_transp);
			    Bitmap b = ((BitmapDrawable)d).getBitmap();
			    ByteArrayOutputStream stream = new ByteArrayOutputStream();
			    b.compress(CompressFormat.PNG, 100, stream);
			    final byte[] logoImageData = stream.toByteArray();

		    	html = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" +
						"<html>\n" +
						"<head>\n" +
						"<style type=\"text/css\">\n" +
						".providerlogo { position: fixed; top: 15px; }\n" + 
						".reviewtext { position: fixed; top: 45px; }\n" + 
						"#p1 { visibility: visible; }\n" + 
						"p { visibility: collapse; }\n" +
						"body { color: white; background-color: rgb(" + backgroundRed + "," + backgroundGreen + "," + backgroundBlue + "); font-family:helvetica neue,arial,sans-serif;font-size:12px }\n" +
						"</style>\n" +
						"</head>\n" +
						"<body>\n" + 
						"<img class=\"providerlogo\" src=\"data:image/png;base64," + Base64.encodeToString(logoImageData, Base64.DEFAULT) + "\" />\n" + 
						"<div class=\"reviewtext\">" + reviewItem.getReview() + "</div>" + 
						"</body></html>";		    	
		    	
		    	
		    	listener = new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						
						String url = reviewItem.getUrl();
						if (url!=null && url.length()>0) {							
							ExternalsReviewItem eri = (ExternalsReviewItem)v.getTag();						
							Intent i = new Intent(Intent.ACTION_VIEW);
							i.setData(Uri.parse(reviewItem.getUrl()));
							startActivity(i);	
						} else {
							Log.w(logTag, "Invalid URL provided for litteratursiden review: " + url);
						}
					}
				};
				
				// Duplicated code, because listener must be final (and sure to be defined)
				v.setOnTouchListener(new View.OnTouchListener() {
					
					@Override
					public boolean onTouch(View v, MotionEvent event) {
						if (event.getAction()==MotionEvent.ACTION_DOWN) {
							listener.onClick(v);
							return true;
						} else {
							return false;
						}
					}
				});
			    v.setOnClickListener(listener);
			    itemLayout.setOnClickListener(listener);
			    overlay.setOnClickListener(listener);
			    // End of duplicated code
		    }
			
		    v.loadData(Base64.encodeToString(html.getBytes(), Base64.DEFAULT), "text/html; charset=utf-8", "base64");

			mainLinearLayout.addView(itemLayout);
	    	mainLinearLayout.addView(inflater.inflate(R.layout.listdivider, null));
			
		}
	}
}
